import {
  CoolController,
  BaseController,
  CoolUrlTag,
  TagTypes,
  CoolTag,
} from '@cool-midway/core';
import { GoodsInfoEntity } from '../../entity/info';
import { GoodsInfoService } from '../../service/info';
import { GoodsTypeEntity } from '../../entity/type';
import { LessThan, MoreThan } from 'typeorm';
import { Body, Inject, Post, Provide } from '@midwayjs/decorator';
import { GoodsClassEntity } from '../../entity/class';

/**
 * 文章信息
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['page', 'info', 'list', 'update'],
})
@CoolController({
  api: ['page', 'info', 'update'],
  entity: GoodsInfoEntity,
  service: GoodsInfoService,
  pageQueryOp: {
    keyWordLikeFields: ['title'],
    fieldEq: ['a.status', 'a.typeId', 'a.classId'],
    select: ['a.*', 'b.name as typeName', 'c.name as className', 'c.parentId'],
    where: ctx => {
      const { year, tp, ztype } = ctx.request.body;
      const list: any = [
        // 过滤掉已下架文章
        ['a.status = :status', { status: 1 }],
        ['a.tp = :tp', { tp }],
      ];
      if (ztype) {
        list.push(['a.ztype = :ztype', { ztype }]);
      }
      if (year) {
        list.push(['a.year = :year', { year }]);
      }
      return list;
    },
    join: [
      {
        entity: GoodsTypeEntity,
        alias: 'b',
        condition: 'a.typeId = b.id',
      },
      {
        entity: GoodsClassEntity,
        alias: 'c',
        condition: 'a.classId = c.id',
      },
    ],
  },
})
export class AppGoodsInfoController extends BaseController {
  @Inject()
  service: GoodsInfoService;

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/prev-next')
  async getPrevNext(@Body() info) {
    const { id } = info;

    return this.service.prevNext(id);
  }
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/years')
  async getYears() {
    return this.ok(await this.service.years());
  }
}
